package com.binarysoft.cmdhandler.common.http;

import java.util.Collection;
import java.util.StringTokenizer;

import com.binarysoft.service.common.http.HandlerConfig;
import com.binarysoft.service.common.http.HttpService;

import common.framework.command.handler.AbstractCommandHandler;
import common.framework.command.helper.CommandHelper;
import common.framework.command.server.Terminal;
import common.framework.dsb.annotation.DSBCmd;
import common.framework.dsb.client.DefaultServiceFactory;
import common.framework.dsb.client.ServiceFactory;

@DSBCmd("http")
public class ShowHttpCmdHandler extends AbstractCommandHandler {

	@Override
	public void handle(String args, Terminal terminal) throws Exception {
		terminal.println("");
		StringTokenizer stier = new StringTokenizer(args);
		int count = stier.countTokens();
		if (count < 2) {
			terminal.println(" Usage:");
			terminal.println(" http ls                                      -- list all http handlers.");
			terminal.println("");
			return;
		}
		stier.nextToken();
		String cmd = stier.nextToken();
		if ("ls".equalsIgnoreCase(cmd)) {

			ServiceFactory serviceFactory = new DefaultServiceFactory();
			HttpService httpService = serviceFactory.lookup("DSB/HttpService");
			Collection<HandlerConfig> handlers = httpService.listHandler();

			String[] tableHAD = { "name", "uri", "class name" };
			String[] tableGAP = { "----", "---", "----------" };
			int[] format = { 20, 20, 36 };
			terminal.println(CommandHelper.format(tableHAD, format));
			terminal.println(CommandHelper.format(tableGAP, format));

			for (HandlerConfig config : handlers) {
				Object[] row = { config.getName(), config.getUri(), config.getClassName() };
				terminal.println(CommandHelper.format(row, format));
			}

		} else {
			terminal.println(" Usage:");
			terminal.println(" http ls                                      -- list all http handlers.");
			terminal.println("");
		}
		terminal.println("");

	}

}
